<template>
  <a-table
      :columns="columns"
      :data-source="data"
      :scroll="{ x: 1500, y: 480 }"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
      v-model:pagination="ipagination"
      :loading="loading"
      @change="handleTableChange"
      :custom-row="handleRow"
  >


    <template #bodyCell="{ column, record }">
<!--      <template v-if="column.key === 'title'">-->
<!--        <a>-->
<!--          {{ record.title }}-->
<!--        </a>-->
<!--      </template>-->
      <template v-if="column.key === 'label'">
        <span>
          <a-tag
              v-for="tag in record.label"
              :key="tag"
              :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
          >
            {{ tag.toUpperCase() }}
          </a-tag>
        </span>
      </template>
      <template v-else-if="column.key === 'action'">
        <span>

          <a @click="updateEssay(record.essayId)">更新</a>
          <a-divider type="vertical"/>
        </span>
      </template>
    </template>
  </a-table>
</template>

<script setup>

import {onMounted, reactive, ref, watch} from "vue";
import {useStore} from "vuex";
import request from "@/utils/request";
import {useRouter} from "vue-router";


const selectedRowKeys = ref([])
const store = useStore()
const router = useRouter()

// const dataTotal = ref()
// const currentPage = ref(1)
// const pageSize = ref(10)

const dbData = ref([])
const data = ref([]);
const loading = ref(false)

const ipagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  pageSizeOptions: ['10', '20', '30'],//可选的页面显示条数
  showTotal: (total, range) => {
    return range[0] + "-" + range[1] + " 共" + total + "条"
  }, //展示每页第几条至第几条和总数
  hideOnSinglePage: false, // 只有一页时是否隐藏分页器
  showQuickJumper: false, //是否可以快速跳转至某页
  showSizeChanger: true, //是否可以改变pageSize
})
const pageListVo = reactive({
  page: ipagination.current,
  limit: ipagination.pageSize
})

const isSearchData = ref(false)


function toTheTable(idate) {
  loading.value = true
  if (idate === null)
    idate = []
  ipagination.total = idate.length
  console.log("totalPage:", ipagination.total)

  let essayId = []
  for (let item in idate) {
    essayId.push(idate[item].essayId)
  }
  console.log("essayIdSet:", essayId)
  data.value = idate

  request.post("essay/getlabel/byEssayIdSet", essayId).then(res => {
    console.log("labelSet:", res)
    for (let i in res.data) {
      data.value.filter((p) => {
        if (p.essayId === res.data[i].essayId) {
          p.label = res.data[i].label
          p.key = res.data[i].essayId
        }
      })
    }
    console.log("data:", data.value)
    loading.value = false
  })
  isSearchData.value = true
}

function getList() {
  loading.value = true
  // setTimeout(() => {
  request.post("essay/getlist", pageListVo).then(res => {
    console.log("essay:", res)
    ipagination.total = res.data.total
    console.log("totalPage:", ipagination.total)
    let essayId = []
    for (let item in res.data.list) {
      essayId.push(res.data.list[item].essayId)
    }
    console.log("essayIdSet:", essayId)
    data.value = res.data.list

    request.post("essay/getlabel/byEssayIdSet", essayId).then(res => {
      console.log("labelSet:", res)
      for (let i in res.data) {
        data.value.filter((p) => {
          if (p.essayId === res.data[i].essayId) {
            p.label = res.data[i].label
            p.key = res.data[i].essayId
          }
        })
      }
      console.log("data:", data.value)
      loading.value = false

    })
  })
  // }, 1000);


}

onMounted(() => {
  getList()
  store.commit('setSelectedEssaySet', [])
})

// const showSizeChange=(current,size)=>{
//   console.log(current,size)
// }

// for (let i = 0; i < 5; i++) {
//   data.value.push({
//     key:i,
//     essayId:1,
//     title: `Edrward ${i}`,
//     views: `${i}`,
//     category:`category${i}`,
//     label: [`l1`,`l2`,`l3`],
//     datetime:`12:12:1${i}`,
//     update:`13:13:1${i}`
//   });
// }

const columns = [{
  title: '标题',
  dataIndex: 'title',
  key: 'title',
  width: '26%',
  fixed: 'left',
}, {
  title: '浏览量',
  dataIndex: 'views',
  key: 'views',
  width: '6%',
  sorter: (a, b) => a.views - b.views,
}, {
  title: '类别',
  dataIndex: 'category',
  key: 'category',
  width: '13%',
}, {
  title: '标签',
  key: 'label',
  dataIndex: 'label',
  width: '20%',
}, {
  title: '发布时间',
  key: 'datetime',
  dataIndex: 'datetime',
  width: '13%',
  sorter: (a, b) => a.datetime - b.datetime,
}, {
  title: '上次更新',
  key: 'update',
  dataIndex: 'update',
  width: '13%',
  sorter: (a, b) => a.update - b.update,
}, {
  title: 'Action',
  key: 'action',
  width: '6%',
  fixed: 'right',
}];

const handleRow = (record) => {
  if (!store.getters.getIsReturn.isRe){
    return {
      onClick: () => {
        store.commit(
            'setIsReturn',
            {
              isRe: true,
              rePath: "/admin/essay"
            })
        router.push("/admin/essay/preview/" + record.essayId)
      }
    }
  }


}

const onSelectChange = selectedRowKey => {

  selectedRowKeys.value = selectedRowKey;
  console.log('selectedRowKeys changed: ', selectedRowKey, selectedRowKeys.value);
  store.commit('setSelectedEssaySet', selectedRowKey)
}

const handleTableChange = paginationChange => {
  console.log("paginationChange:", paginationChange)
  ipagination.pageSize = paginationChange.pageSize
  ipagination.current = paginationChange.current
  console.log("ipagination:", ipagination)

  if (!isSearchData.value) {
    pageListVo.limit = ipagination.pageSize
    pageListVo.page = ipagination.current
    console.log("pageListVo:", pageListVo)
    getList()
  }

}

const updateEssay = (essayId) => {
  console.log("更新")
  store.commit(
      'setIsReturn',
      {
        isRe: true,
        rePath: "/admin/essay"
      })
  router.push("/admin/essay/update/" + essayId)
}

watch(() => store.getters.getSearchSet, nowValue => {
  console.log("watch:", nowValue)
  toTheTable(nowValue)
})

</script>

